<template>
    <div>
        <!--最右边的导航-->
        <div id="showIframe">
            <i class="fa fa-chevron-left" aria-hidden="true" v-on:click="showIframe = !showIframe"></i>
            <transition name="fade">
                <div id="iframe_" v-if="showIframe">
                </div>
            </transition>
        </div>
        <!--来电话接电话的小窗口-->
        <div id="incomePhone">
            <div class=" " role="group" aria-label="">
                <button id="accept" type="submit" class="btn btn-info" @click="Accept()">接  听</button>
                <button id="reject" type="submit" class="btn btn-danger" @click="Reject()" style="margin-left:1px">拒  接</button>
            </div>
        </div>
        <!--表单-->
        <div class="container-fluid" allow="microphone; camera" id="green_red">
            <div class="header_nav">
                <a href="#">
                    <img src=" " title="绿索智能"/>
                </a>
                <div class="el-col-3">
                    <small class="text-muted" id="header_ygmc">├─员工名称： {{$cache_.getCookie('user')}}</small><br/>
                    <small class="text-muted" id="header_yggh">├─员工工号： {{$cache_.getCookie('yggh')}}</small><br/>
                    <small class="text-muted" id="header_ygzx">├─员工坐席： {{$cache_.getCookie('zuoxi')}}</small>
                </div>
                <div class="el-col-3">
                    <small class="text-muted">公司： {{JSON.parse($cache_.getCookie('dlxl_'))[0]}}</small><br/>
                    <small class="text-muted">└──部门： {{JSON.parse($cache_.getCookie('dlxl_'))[1]}}</small><br/>
                    <small class="text-muted">└────职位： {{JSON.parse($cache_.getCookie('dlxl_'))[2]}}</small>
                </div>
                <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="60px">
                    <el-form-item prop="destination">
                        <el-input v-model="form.destination" size="mini"  placeholder="输入需要外拨的电话号码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button :disabled="!((!isCalling)&&signin)" @click="Call()" size="mini">外呼</el-button>
                        <el-button :disabled="!(isCalling&&signin)" @click="Hangup()" size="mini">挂断</el-button>
                        <el-button type="primary" :disabled="signin" @click="active_signin()" size="mini">签入</el-button>
                        <el-button :disabled="!signin" @click="active_signout()" size="mini">签出</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="warning" @click="logout()" size="mini">注销</el-button>
                    </el-form-item>
                    <div class="form-group sign">
                        <iframe allow="microphone; camera" style="display:none" height="0" width="0" id="webphoneframe"></iframe>
                        <small class="text-muted" id="signin" style="width: 13em;color: #f85506!important;">{{signinNotice}}</small>
                    </div>
                </el-form>
            </div>
            <div id="video_container" style="display: none;"></div>
            <audio src="" id="sound" controls="controls" loop="false" hidden="true"></audio>
            <video id="remoteVideo" hidden="true"/>
            <video id="localVideo" hidden="true" muted="true" />
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
    import {formatDate} from '../../common/js/util';
    export default {
        props: {},
        data() {
            return {
                form:{
                    zuoxi: this.$cache_.getCookie('zuoxi'),
                    destination: "",
                },
                showIframe: false,
                signin: false,// 是否签入
                isCalling: false,// 是否正在通话 true,通话中，false，为通话中
                signinNotice: "未连接",// 是否签入
                call_time: 122222222222,
                nat: window.nat,
                sessions: "",
                userAgent: Object,
                callingOut: false,
                ua: {},
                sessionUIs :{},
                sessionUI:{},
                isRing:false,//表示对方电话还没响铃
                callLoading:true,
                config:{},
                intervalIndex:0,
                mysockets:0,
                rules: {
                    destination: [
                        { required: true, message: '请输入要拨打的电话号码', trigger: 'blur' },
                    ],
                }
            }
        },
        created: function(){
            this.$nextTick(function () {
                this.config = {
                    displayName:"1004",
                    uri: get.zuoxi+"@"+nat,
                    authorizationUser: "1004",
                    password: "123456",
                    wsServers: "wss://"+nat+":7443",
                    ua_uri: "1000",
                    realm: nat,
                    ua_uris: "1000@"+nat,
                    traceSip: true
                };
                this.config.uri = this.form.zuoxi+"@"+this.nat;
                this.config.authorizationUser = this.form.zuoxi;
                this.config.displayName = this.form.zuoxi;
                this.config.ua_uris = this.form.destination + "@"+this.nat;
            });
        },
        updated: function(){
            this.$nextTick(function () {
                this.config.uri = this.form.zuoxi+"@"+this.nat;
                this.config.authorizationUser = this.form.zuoxi;
                this.config.displayName = this.form.zuoxi;
                this.config.ua_uris = this.form.destination + "@"+this.nat+":7443";
            });
        },
        mounted:function(){
            this.$nextTick(function () {
            });
        },
        methods: {
            autoPlay: function (src) {
                setTimeout(function () {
                    var sound = $('#sound');
                    sound.attr("src",src);
                    sound[0].play();
                },3000);
            },
            closePlay: function () {
                setTimeout(function () {
                    var sound = $('#sound');
                    if (sound.onplaying) {
                        sound[0].pause();
                    }
                },100);
            },
            active_signin: function () {
                var that = this;
                if (typeof (this.form.zuoxi) === 'undefined' || this.form.zuoxi === null || this.form.zuoxi.length < 1) {
                    layui.layer.msg('输入需要显示的姓名.');
                    $("#username").focus();
                    return;
                }
                JsSIP.C.SESSION_EXPIRES = 280;//防止打电话session过期
                var socket = new JsSIP.WebSocketInterface(this.config.wsServers);
                var config_ = {
                    sockets  : [ socket ],
                    uri      : this.config.uri,
                    password : this.config.password,
                };
                that.ua = new JsSIP.UA(config_);
                that.ua.on('registered', function (res) {//签入
                    that.signinNotice = "正在签入...";
                    //将后台的该用户变成状态 为 真正上线
                    that.$post('cti-manager/set-fs',
                        {data:{
                                1:"callcenter_config tier set state support@default "+that.form.zuoxi+"@${domain} Ready",
                                2:"callcenter_config agent set status "+that.form.zuoxi+"@${domain} Available",
                                3:"callcenter_config agent set state "+that.form.zuoxi+"@${domain} 'Waiting'",
                            },
                            zuoxi:that.form.zuoxi,
                            action:"signin",
                        }
                    )
                        .then((response) => {//这里使用了ES6的语法
                            if (response.data == 1) {
                                layer.msg("上线成功！",{icon:1});
                                that.signin = true;
                                that.signinNotice = '已经连接 (已经签入)';
                                let data = {zuoxi:that.form.zuoxi,time:(new Date().getTime()),sign:"sign"};
                                that.$post('cti-manager/save-zlg',//坐席登录后定时 提示freeswitch是否在线的标志数据库
                                    data
                                ).then((response) => {
                                    //签入成功就定时发送数据到后台 10s发送一次
                                    myloop();
                                    function myloop(){
                                        that.intervalIndex = setTimeout(() => {
                                            let data2 = {zuoxi:that.form.zuoxi,time:(new Date().getTime()),sign:"loop"};
                                            that.$post('cti-manager/save-zlg',//坐席登录后定时 提示freeswitch是否在线的标志数据库
                                                data2
                                            ).then((response) => {
                                                myloop();
                                            });
                                        },10000);
                                    }
                                }).catch((response) => {
                                    layer.msg("错误！",{icon:2});
                                    clearInterval(that.intervalIndex);
                                });
                            }else{
                                layer.msg("上线失败！",{icon:2});
                                clearInterval(that.intervalIndex);
                            }
                        }).catch((response) => {
                        layer.msg("错误！",{icon:2});
                        clearInterval(that.intervalIndex);
                    });
                });
                that.ua.on('unregistered', function () {//签出
                    that.signinNotice = "正在签出...";
                    //将后台的该用户变成状态 为 真正上线
                    that.$post('cti-manager/set-fs',
                        {data:{
                                1:"callcenter_config tier set state support@default "+that.form.zuoxi+"@${domain} Ready",
                                2:"callcenter_config agent set status "+that.form.zuoxi+"@${domain} 'Logged Out'",
                            },
                            zuoxi:that.form.zuoxi,
                            action:"signout",
                        }
                    )
                        .then((response) => {//这里使用了ES6的语法
                            if (response.data == 1) {
                                layer.msg("下线成功！",{icon:1});
                                that.signin = false;
                                that.signinNotice = '已经下线 (已经签出)';
                                clearInterval(that.intervalIndex);
                                let data = {zuoxi:that.form.zuoxi,time:(new Date().getTime()),sign:"unsign"};
                                that.$post('cti-manager/save-zlg',//坐席登录后定时 提示freeswitch是否在线的标志数据库
                                    data
                                ).then((response) => {
                                }).catch((response) => {
                                });
                            }else{
                                layer.msg("下线失败！",{icon:2});
                                clearInterval(that.intervalIndex);
                            }
                        }).catch((response) => {
                        layer.msg("错误！",{icon:2});
                        clearInterval(that.intervalIndex);
                    });
                });
                that.ua.on('registrationFailure', function() {
                    that.signinNotice = '签入失败';
                });
                that.ua.on('newRTCSession', function(e){//来电话
                    if (e.originator=="remote") {//远方打来的
                        that.session = e.session;
                        that.session.on('connecting',function(){//正在响铃
                            $("#incomePhone").css("display","block");
                            that.autoPlay("../../static/sound/in.wav");
                            that.isCalling = true;
                            that.$router.push("/hotCenter/hwzx?phone="+that.session['remote_identity']['uri']['user']+"&key="+Math.random());
                        });
                        that.session.on('accepted',function(e){//接听通过 progress connecting terminated confirmed ended failed hold unhold muted unmuted
                            $("#incomePhone").css("display","none");
                            that.closePlay();
                            that.isCalling = true;
                            var remoteVideo = document.getElementById('remoteVideo');
                            var localVideo = document.getElementById('localVideo');
                            setTimeout(function () {
                                var pc = that.session._connection
                                var remoteStream = new MediaStream()
                                pc.getReceivers().forEach(function(receiver) {
                                    remoteStream.addTrack(receiver.track)
                                });
                                remoteVideo.srcObject = remoteStream
                                remoteVideo.play();

                                var stream = new MediaStream()
                                pc.getSenders().forEach(function(sender) {
                                    stream.addTrack(sender.track);
                                });
                                localVideo.srcObject = stream;
                                localVideo.play();
                            },100);
                        });
                        that.session.on('ended',function(){//结束通话
                            that.hungupAfter();
                        });
                        that.session.on('failed',function(){//通话中
                            that.hungupAfter();
                        });
                    }
                    if (e.originator=="local") {//本地打出去的
                    }
                });
                that.ua.start();//开始签入
            },
            Call: function(){//打电话
                var that = this;
                var eventHandlers = {
                    'progress': function(e) {
                        that.signinNotice = '正在响铃...';
                    },
                    'failed': function(e) {
                        that.signinNotice = '呼叫取消';
                        that.hungupAfter();
                    },
                    'ended': function(e) {
                        that.signinNotice = '呼叫结束';
                        that.hungupAfter();
                    },
                    'confirmed': function(e) {
                        that.signinNotice = '正在通话';
                    },
                };
                var options = {
                    'eventHandlers'    : eventHandlers,
                    'mediaConstraints' : { 'audio': true, 'video': false }
                };
                if (typeof (that.form.destination) === 'undefined' || that.form.destination === null || that.form.destination.length < 1) {
                    layer.msg('输入需要拨打出去的号码！');
                    $("#destnumber").focus();
                    return;
                };
                that.isCalling = true;
                that.autoPlay("../../static/sound/out.mp3");
                that.session = that.ua.call(that.form.destination+"@"+this.nat+":7443", options);
                var remoteVideo = document.getElementById('remoteVideo');
                var localVideo = document.getElementById('localVideo');
                var track = 0;
                that.session.on('connecting', function () {//正在响铃
                    if (track==0) {// 表示对方开始响铃了会接到这个消息
                        that.isRing = true;
                        that.isCalling = true;
                    }
                    if (track==1){
                        setTimeout(function () {
                            that.closePlay();
                            var pc = that.session._connection
                            var remoteStream = new MediaStream()
                            pc.getReceivers().forEach(function(receiver) {
                                remoteStream.addTrack(receiver.track)
                            });
                            remoteVideo.srcObject = remoteStream
                            remoteVideo.play();

                            var stream = new MediaStream()
                            pc.getSenders().forEach(function(sender) {
                                stream.addTrack(sender.track);
                            });
                            localVideo.srcObject = stream;
                            localVideo.play();
                        },300)
                    }
                    track++;
                });
            },
            Hangup: function(){
                var that = this;
                var session = that.session;
                if (session.terminate) { //挂断
                    session.terminate();
                    that.hungupAfter();
                }
            },
            Reject: function(){
                this.Hangup();//拒接
            },
            Accept: function(){
                this.session.answer()
            },
            hungupAfter: function() {
                var that = this;
                $("#incomePhone").css("display","none");
                layer.close(that.callLoading);
                setTimeout(function () {
                    that.closePlay();
                },800);
                that.isCalling = false;
            },
            active_signout: function () {//签出
                if (!this.ua) return;
                if (this.ua.isRegistered()) {
                    clearInterval(this.intervalIndex);
                    this.ua.stop();
                }
            },
            logout:function () {//退出
                this.$confirm("确定注销登录？", '确认信息')
                    .then(() => {
                        this.$post('site/front-logout',{})
                            .then((response) => {//这里使用了ES6的语法
                                if (response.data) {
                                    this.$cache_.delCookie('user');
                                    this.$cache_.delCookie('isLogin');
                                    this.$router.push({path: '/login'})
                                    this.$cache_.removeLocalStorage('navTabList')
                                    this.$message({message:'注销成功！',type:'success'});
                                }
                            }).catch((response) => {
                            this.$message({meaasge:'注销失败！',type:'success'});
                        });
                    })
            },
        },
        filters: {
            dateFormat: function(date,fmt){
                return formatDate(new Date(date), fmt);
            }
        },
    }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    #showIframe{
        position: fixed;
        right: 0px;
        z-index: 9999;
        line-height: 100%;
        height: 100%;
        text-align: center;
        vertical-align: middle;
        display: flex;
        justify-content:center;
        align-items:Center;
        i{
            font-size: 20px;
            color:#aaaaaa;
            cursor:pointer;
        }
        i:hover{
            font-size: 20px;
            color:#cccccc;
        }
        #iframe_{
            display: block;
            width: 400px;
            background-color: #ddddddaa;
            height: 100%;
        }
    }
    #incomePhone{
        display: none;
        width: auto;
        height: 60px;
        position: fixed;
        z-index: 9999;
        right: 0px;
        vertical-align: middle;
        line-height: 60px;
        top: 2px;
        right: 2px;
        background-color: #dddddd88;
        border-radius:18px;
        button{
            margin: 0px 20px;
            flex:1;
        }
    }
    input { display: inline-block; width: 13em; }
    .container-fluid {
        background-color: #333333;
    }
    .header_nav{
        display: flex;
        padding: 5px;
        >a{
            flex: 1;
        }
        .header_nav_right{
            float: right;
            input{
            }
        }
    }
    .sign .active{
        background-color: #f85506!important;
        border: 1px solid #f85506!important;
    }
    .radio label{
        color:#f85506;
        dispaly:block;
        padding: 1px;
        vertical-align: middle;
        input{
            vertical-align: middle;
        }
    }
    .text-muted{
        color:#f85506;
    }
    .site-doc-color p{
        color: #f85506;
    }
    .form-group {
        text-align: center;
        display: inline-block;
        padding: 10px 10px;
        margin: 0px;
        height: auto;
        vertical-align: center;
    }
    .top_nav span,p {
        display: inline-block;
        color: #fff;
        font-size: 14px;
        margin: 0px 0px;
        padding: 0px 0px;
        line-height: 0px;
    }
    .img {
        display: block;
        width: 30px;
        height: 30px;
    }
    .top_nav label {
        color: #fff;
        font-size: 14px;
    }
    label {
        display: inline-block;
        margin-bottom: 0rem;
    }
</style>
